package homework7;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

//ctrl+shift+t 找jar包里的
//ctrl+shift+r 找自己写的东西
/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			System.out.println("/test2/UploadServlet");
			upload(request);
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		request.getRequestDispatcher("/homework7/Upload.jsp").forward(request, response);
	}
	
	private void upload(HttpServletRequest request) throws FileUploadException, IOException {
		 DiskFileItemFactory factory=new DiskFileItemFactory();
		// Servlet进行文件上传时，可以把文件系统当中的一个东西（factory）进行实例化
		 ServletFileUpload upload=new ServletFileUpload(factory);
		// 用upload解析req---upload.parseRequest(req)
		// 将请求解析出来的东西变成文件条目--FileItem
		 List<FileItem> items=upload.parseRequest(request);
		 int i=1;
		 for(FileItem item:items) {
			 if(item.isFormField()) {//非文件域的表单元素/普通的表单元素
				 String value=item.getString();
				 value=new String(value.getBytes("ISO-8859-1"),"UTF-8");
//				 System.out.println("1111--"+value);
				 request.setAttribute("code", value);
			 }else {//文件域的表单元素
//				 String filename=item.getName();
				 String filename = getFilename(item);
//				 System.out.println("22222---"+filename);
//				 filename=getFilename(item);
//				 System.out.println("new==="+filename);
				// 把上传上来的流写入到某个路径下
				 FileOutputStream fos=new FileOutputStream("D:\\documents\\"+filename);
				// 输入流，把上传的每一个文件的输入流得到
				 InputStream is=item.getInputStream();
				 
				 int len=-1;
				 byte[] b=new byte[1024*1024];
				 while(-1!=(len=is.read(b))) {
					 fos.write(b, 0, len);
				 }
				 fos.flush();
				 is.close();
				 fos.close();
				 fos=null;
				 is=null;
				 request.setAttribute("fn"+ i++, filename);// 每一次获得不一样的图片名
			 }
		 }
	}
	
	private String getFilename(FileItem item) {
		String fn=item.getName();
		String uuid=UUID.randomUUID().toString();
		//2-时间毫秒数获得随机数
		//fn.substring(fn.lastIndexOf(".")); 获得后缀名
		return uuid+fn.substring(fn.lastIndexOf("."));
	}
}
